/*
* Copyright 2022 Beijing Zitiao Network Technology Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


package net.bytedance.security.app.web

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.bytedance.security.app.getConfig
import java.io.File
import java.util.concurrent.atomic.AtomicInteger

class VulnerabilityFileSaver : VulnerabilitySaver {
    val path: String
    private val count = AtomicInteger(0)

    init {
        val base = getConfig().outPath
        val vulnerabilityDirectory = "$base/vulnerability"
        val vulnerabilityFile = File(vulnerabilityDirectory)
        if (!vulnerabilityFile.exists()) {
            vulnerabilityFile.mkdirs()
        }
        path = vulnerabilityDirectory
    }

    override suspend fun saveVulnerability(outBuf: ByteArray, fileName2: String): String = withContext(Dispatchers.IO) {
        val n = count.getAndAdd(1)
        val fileName = "$path/$n-$fileName2"
        val f = File(fileName)
        try {
            f.writeBytes(outBuf)
            return@withContext f.absolutePath
        } catch (ex: Exception) {
            ex.printStackTrace()
            return@withContext ""
        }
    }
}